﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text.Json;
using JsonSerializer = Newtonsoft.Json.JsonSerializer;

namespace MyJson
{
    /// <summary>
    /// Json转换帮助类
    /// </summary>
    public class MyJsonHelper
    {
        /// <summary>
        /// 将对象序列化为JSON格式
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns>Json字符串</returns>
        public static string SerializeObjectToString(object obj)
        {
            JsonSerializerSettings setting = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            };
            string strJson = JsonConvert.SerializeObject(obj, setting);
            return strJson;
        }

        /// <summary>
        /// 解析JSON字符串生成对象实体
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="strJson">Json字符串</param>
        /// <returns>对象实体</returns>
        public static T DeserializeJsonToObject<T>(string strJson) where T : class
        {
            JsonSerializer serializer = new JsonSerializer();
            StringReader sr = new StringReader(strJson);
            object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
            T t = o as T;
            return t;
        }

        /// <summary>
        /// 解析JSON数组生成对象实体集合
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="strJson">Json数组字符串</param>
        /// <returns>对象实体集合</returns>
        public static List<T> DeserializeJsonToList<T>(string strJson) where T : class
        {
            JsonSerializer serializer = new JsonSerializer();
            StringReader sr = new StringReader(strJson);
            object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
            List<T> list = o as List<T>;
            return list;
        }

        /// <summary>
        /// 将字符串转换成Json对象
        /// </summary>
        /// <param name="strJson">对象的Json字符串</param>
        /// <returns>Json对象</returns>
        public static JObject JsonParseToJObject(string strJson)
        {
            JObject result = JObject.Parse(strJson);
            return result;
        }
    }
}
